package com.yhao.stock.common.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

/**
 * @desc 日期处理工具类
 */
public class DateUtil {

    public static String getFirstDayOfWeek(int year, int week) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置周
        cal.set(Calendar.WEEK_OF_YEAR, week);
        //设置该周第一天为星期一
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfWeek = sdf.format(cal.getTime());

        return firstDayOfWeek;
    }


    public static String getDate() {
        return getDate("yyyyMMddHHmmss");
    }

    public static String getCommonDate() {
        return getDate("yyyy-MM-dd HH:mm:ss");
    }

    public static String getSimpleDate() {
        return getDate("yyyy-MM-dd");
    }

    /**
     * @param format
     * @param count
     * @return
     * @desc 获取当前月的前N个月份
     */
    public static String getBeforeMonth(String format, int count) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -count);
        Date m = c.getTime();
        return sdf.format(m);

    }

    public static String getDate(String fmt) {
        Date myDate = new Date(System.currentTimeMillis());
        SimpleDateFormat sDateformat = new SimpleDateFormat(fmt);
        return sDateformat.format(myDate);
    }


    public static String getDateFormat(Date date, String fmt) {
        SimpleDateFormat sDateformat = new SimpleDateFormat(fmt);
        return sDateformat.format(date);
    }

    public static String getStrFormatToFormat(String date, String fmt1, String fmt2) {
        Date date1 = DateUtil.getUtilDate(date, fmt1);
        return DateUtil.getDateFormat(date1, fmt2);
    }


    /**
     * @param dateA
     * @param dateB
     * @return
     * @desc 日期比较  大于等于返回true  小于返回false
     */
    public static boolean compareDate(String dateA, String dateB) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date dtA = df.parse(dateA);
            Date dtB = df.parse(dateB);
            if (dtA.getTime() >= dtB.getTime()) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            //e.printStackTrace();
            return false;
        }
    }


    public static Calendar getCal(String strdate, String fmt) {
        Calendar cal = null;
        try {
            if ((strdate == null) || (fmt == null)) {
                return cal;
            }
            SimpleDateFormat nowDate = new SimpleDateFormat(fmt);
            Date d = nowDate.parse(strdate, new ParsePosition(0));
            if (d == null) {
                return cal;
            }
            cal = Calendar.getInstance();
            cal.clear();
            cal.setTime(d);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cal;
    }

    /**
     * @return
     * @desc 获取下个月
     */
    public static String getNextMonth() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1); // 设置为上一个月
        date = calendar.getTime();
        String yearAndDay = dateFormat.format(date);
        return yearAndDay;
    }


    public static Date getUtilDate(String stringDate, String format) {
        SimpleDateFormat df;
        Date date = null;
        df = new SimpleDateFormat(format);

        try {
            date = df.parse(stringDate);
        } catch (ParseException pe) {
            pe.printStackTrace();
        }

        return date;
    }


    public static int getWeekOfYear(String strdate, String fmt) {
        int ret = -1;
        try {
            if ((strdate == null) || (fmt == null)) {
                return ret;
            }
            Calendar cal = getCal(strdate, fmt);
            if (cal == null) {
                return ret;
            }
            ret = cal.get(3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * @param count  数量
     * @param period 周期类型：1、年  2、月 3、日 4、时 5、分 6、，秒
     * @return
     * @desc 按照周期获取之前的日期
     */
    public static String getBeforeDayByPeriod(int count, int period) {
        LocalDate today = LocalDate.now(); // 获取今天的日期
        LocalDate oldDate = null;
        if (period == 1) {// 年
            oldDate = today.minus(count, ChronoUnit.YEARS);
        } else if (period == 2) {
            oldDate = today.minus(count, ChronoUnit.MONTHS);
        } else if (period == 3) {
            oldDate = today.minus(count, ChronoUnit.DAYS);
        } else {
            oldDate = today;
        }
        return oldDate.format(DateTimeFormatter.ISO_DATE);
    }

    public static String getDayOfWeek(String strDate, String fmt) {
        String sWeek = null;
        try {
            if ((strDate == null) || (fmt == null)) {
                return sWeek;
            }
            Calendar cal = getCal(strDate, fmt);
            if (cal == null) {
                return sWeek;
            }
            int iWeek = cal.get(7);
            sWeek = "" + ((iWeek - 1 != 0) ? iWeek - 1 : 7);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sWeek;
    }


    public static String getBeforeTimeByMinute(String deftime, String oldfmt,
                                               int timediff, String newfmt) {
        String rq = null;
        try {
            if ((deftime == null) || (deftime.equals(""))) {
                return rq;
            }
            Calendar cal = getCal(deftime, oldfmt);
            if (cal == null) {
                return rq;
            }
            cal.add(12, -timediff);
            SimpleDateFormat sdf = new SimpleDateFormat(newfmt);
            rq = sdf.format(cal.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rq;
    }

    public static String getBeforeTimeByDay(String deftime, String oldfmt,
                                            int timediff, String newfmt) {
        String rq = null;
        try {
            if ((deftime == null) || ("".equals(deftime))) {
                return rq;
            }
            Calendar cal = getCal(deftime, oldfmt);
            if (cal == null) {
                return rq;
            }
            cal.add(Calendar.DAY_OF_MONTH, -timediff);
            SimpleDateFormat sdf = new SimpleDateFormat(newfmt);
            rq = sdf.format(cal.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rq;
    }

    public static String getBeforeTimeByMonth(String deftime, String oldfmt,
                                              int timediff, String newfmt) {
        String rq = null;
        try {
            if ((deftime == null) || (deftime.equals(""))) {
                return rq;
            }
            Calendar cal = getCal(deftime, oldfmt);
            if (cal == null) {
                return rq;
            }
            cal.add(2, -timediff);
            SimpleDateFormat sdf = new SimpleDateFormat(newfmt);
            rq = sdf.format(cal.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rq;
    }

    public static String getDateByDay(String fmt, int day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        return new SimpleDateFormat(fmt).format(cal.getTime());
    }

    public static String fmtDate(String mydate, String oldfmt, String newfmt) {
        String restr = null;
        try {
            if ((mydate == null) || (oldfmt == null) || (newfmt == null)) {
                return restr;
            }
            SimpleDateFormat newDate = new SimpleDateFormat(newfmt);
            Calendar cal = getCal(mydate, oldfmt);
            if (cal == null) {
                return restr;
            }
            restr = newDate.format(cal.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restr;
    }

    public static String getAfterDateByMillisecond(Date date, long timespan,
                                                   String newfmt) {
        long milli_second = date.getTime();
        Date new_Date = new Date(milli_second + timespan);
        SimpleDateFormat sDateformat = new SimpleDateFormat(newfmt);
        return sDateformat.format(new_Date).toString();
    }

    public static String getCurrentTimeByFormat(String format) {
        if (format == null || "".equals(format)) {
            return "";
        }
        String result = "";
        String nowDate = getDate("yyyy-MM-dd HH:mm:ss.SSS");
        if ("yyyy".equalsIgnoreCase(format)) {
            result = nowDate.substring(0, 4);
        } else if ("MM".equals(format)) {
            result = nowDate.substring(nowDate.indexOf("-") + 1,
                    nowDate.lastIndexOf("-"));
        } else if ("dd".equalsIgnoreCase(format)) {
            result = nowDate.substring(nowDate.lastIndexOf("-") + 1,
                    nowDate.indexOf(" "));
        } else if ("HH".equalsIgnoreCase(format)) {
            result = nowDate.substring(nowDate.indexOf(" ") + 1,
                    nowDate.indexOf(":"));
        } else if ("mm".equals(format)) {
            result = nowDate.substring(nowDate.indexOf(":") + 1,
                    nowDate.lastIndexOf(":"));
        } else if ("ss".equalsIgnoreCase(format)) {
            result = nowDate.substring(nowDate.lastIndexOf(":") + 1,
                    nowDate.indexOf("."));
        } else if ("SSS".equalsIgnoreCase(format)) {
            result = nowDate.substring(nowDate.indexOf(".") + 1);
        }
        return result;
    }

    public static int differMonth(String firstDate, String secondDate, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);


        Calendar bef = null;
        Calendar aft = null;
        try {
            bef = Calendar.getInstance();
            aft = Calendar.getInstance();
            bef.setTime(sdf.parse(firstDate));
            aft.setTime(sdf.parse(secondDate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        surplus = surplus <= 0 ? 1 : 0;
        return (Math.abs(month + result) + surplus);
    }

    public static int daysBetweenByDay(Date adtDate1, Date adtDate2) {
        long quot = adtDate1.getTime() - adtDate2.getTime();
        return (int) (quot / 86400000);
    }

    public static Long dayMinDay(Date d1, Date d2) {
        return d2.getTime() - d1.getTime();
    }

    public static Long dayMinDay(String d1, String d2) {
        Date dt1 = DateUtil.getUtilDate(d1, "yyyy-MM-dd HH:mm:ss");
        Date dt2 = DateUtil.getUtilDate(d2, "yyyy-MM-dd HH:mm:ss");
        return dt2.getTime() - dt1.getTime();
    }

    public static String getStringDateSort() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(new Date());
        return dateString;
    }

    // public static void main(String[] args) {
    //     final String beforeDayByPeriod = getBeforeDayByPeriod(1, 3);
    //     System.out.println(beforeDayByPeriod);
    // }
}
